package com.qing.springcloud.dao;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import lombok.extern.slf4j.Slf4j;
import com.qing.springcloud.entity.Message;
import com.qing.springcloud.mapper.MessageMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;


import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * (message)数据DAO
 *
 * @author kancy
 * @since 2025-07-09 19:32:19
 * @description 由 Mybatisplus Code Generator 创建
 */
@Slf4j
@Repository
public class MessageDao extends ServiceImpl<MessageMapper, Message> {

    @Autowired
    private  MessageMapper messageMapper;

    public void updateStatusToDelivered(List<String> msgIds, Long receiverId) {
        log.info("更新消息状态为已送达: msgIds={}, receiverId={}", msgIds, receiverId);
        messageMapper.updateStatusToDelivered(msgIds, receiverId, DateUtil.date());
    }

    public void updateStatusToRead(List<String> msgIds, Long receiverId, Date date) {
        log.info("更新消息状态为已读: msgIds={}, receiverId={}, date={}", msgIds, receiverId, date);
        messageMapper.updateStatusToRead(msgIds, receiverId, date);
    }

    public Page<Message> findPrivateChatHistory(Long userId, Long friendId, Page<Message> pageable) {
        log.info("查询私聊历史: userId={}, friendId={}, pageable={}", userId, friendId, pageable);
        return  lambdaQuery().eq(Message::getSenderId, userId)
                .eq(Message::getReceiverId, friendId)
                .orderByDesc(Message::getSendTime)
                .page(pageable);
    }

    public Page<Message> findByReceiverIdAndChatType(Long groupId, Integer code, Page<Message> pageable) {
        log.info("查询群聊历史: groupId={}, code={}, pageable={}", groupId, code, pageable);
        return lambdaQuery().eq(Message::getReceiverId, groupId)
                .eq(Message::getChatType, code)
                .orderByDesc(Message::getSendTime)
                .page(pageable);
    }

    public Optional<Message> findByMsgId(String msgId) {
        return Optional.ofNullable(lambdaQuery().eq(Message::getMsgId, msgId).one());
    }


}